package xin.yangshuai.basic01.download;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * DownloadController
 *
 * @author shuai
 * @date 2022/5/28
 */
@RestController
@RequestMapping("download")
public class DownloadController {

    @RequestMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File("E:\\down\\123.png");
        byte[] bytes = Files.readAllBytes(file.toPath());
        DownloadController.download(bytes, "图片1.png", request, response);
    }

    public static void download(byte[] bytes, String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取请求的浏览器
        String newFilename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        System.out.println(newFilename);
        String attachmentFileName = "attachment;fileName=" + newFilename;

        byte[] buffer = new byte[1024];
        //强制下载
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", attachmentFileName);
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
        OutputStream outputStream = response.getOutputStream();
        int len;
        while ((len = bis.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
    }

    private static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT");
        if (userAgent.indexOf("Firefox") != -1) {
            return "Firefox";
        }
        return null;
    }
}
